﻿namespace Dcms.Config
{
    using System;
    using System.Timers;
    using System.Web;

    public class WebSiteConfigs
    {
        private static DateTime _fileoldchange;
        private static string _filepaht = "~/SystemConfig/WebSiteInfo.config";
        private static WebSiteConfigInfo _websiteconfiginfo = null;
        private static object lockHelper = new object();

        public WebSiteConfigs()
        {
            _websiteconfiginfo = Deserialize(_filepaht);
        }

        public WebSiteConfigs(string configFilePath)
        {
            _filepaht = configFilePath;
            _websiteconfiginfo = Deserialize(configFilePath);
        }

        private static string CheckConfigPath(string FilePath)
        {
            return HttpContext.Current.Server.MapPath(FilePath);
        }

        public static WebSiteConfigInfo Deserialize(string configFilePath)
        {
            if (_websiteconfiginfo == null)
            {
                _filepaht = configFilePath;
                _websiteconfiginfo = (WebSiteConfigInfo) DefaultConfigFileManager.DeserializeInfo(CheckConfigPath(configFilePath), typeof(WebSiteConfigInfo));
                return _websiteconfiginfo;
            }
            return _websiteconfiginfo;
        }

        public static WebSiteConfigInfo GetConfig()
        {
            return _websiteconfiginfo;
        }

        public static void ResetConfig()
        {
            _websiteconfiginfo = (WebSiteConfigInfo) DefaultConfigFileManager.DeserializeInfo(CheckConfigPath(_filepaht), typeof(WebSiteConfigInfo));
        }

        public static bool Serialiaze(WebSiteConfigInfo configinfo, string configFilePath)
        {
            lock (lockHelper)
            {
                _websiteconfiginfo = configinfo;
                return DefaultConfigFileManager.SaveConfig(CheckConfigPath(configFilePath), configinfo);
            }
        }

        private static void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            ResetConfig();
        }
    }
}

